package com.newthread.android.ui.bbs;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.*;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadBatchListener;
import com.newthread.android.R;
import com.newthread.android.activity.main.BaseSFActivity;
import com.newthread.android.bean.remoteBean.StudentUser;
import com.newthread.android.bean.remoteBean.bbs.Post;
import com.newthread.android.bean.remoteBean.bbs.PostImage_1;
import com.newthread.android.manager.BmobRemoteDateManger;
import com.newthread.android.util.FileUtil;
import com.newthread.android.util.ImageUtil;
import com.newthread.android.util.Loger;
import com.newthread.android.util.MyPreferenceManager;
import com.squareup.picasso.Picasso;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import me.nereo.multi_image_selector.MultiImageSelectorFragment;
import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jindongping on 15/6/21.
 */
public class BbsWritePostActivity extends BaseSFActivity implements MultiImageSelectorFragment.Callback {
    private Context context;
    private static final int REQUEST_IMAGE = 2;
    private GridViewBaseAdapter mImageAdapter;
    private ArrayList<String> mSelectPath;

    @ViewInject(id = R.id.bbs_write_title)
    private EditText title;
    @ViewInject(id = R.id.bbs_write_content)
    private EditText content;
    @ViewInject(id = R.id.bbs_write_gridview)
    private GridView gridView;
    @ViewInject(id = R.id.bbs_write_add_photo)
    private Button addPhoto;
    @ViewInject(id = R.id.bbs_write_clean_photo)
    private Button cleanPhoto;

    private ProgressDialog dialog;


    private int mItemSize;
    private GridView.LayoutParams mItemLayoutParams
            = new GridView.LayoutParams(GridView.LayoutParams.MATCH_PARENT, GridView.LayoutParams.MATCH_PARENT);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bbs_write_post);
        FinalActivity.initInjectedView(this);
        getSupportActionBar().setTitle("发帖");
        initView();

    }

    private void initView() {
        setEditText(title);
        setEditText(content);
        dialog = new ProgressDialog(BbsWritePostActivity.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCancelable(false);
        context = getApplicationContext();
        addPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToMultiImageSelector();
            }
        });
        cleanPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectPath != null) {
                    mSelectPath.clear();
                    mImageAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void setEditText(EditText editText) {
        editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        //文本显示的位置在EditText的最上方
        editText.setGravity(Gravity.TOP);
        //改变默认的单行模式
        editText.setSingleLine(false);
        //水平滚动设置为False
        editText.setHorizontallyScrolling(false);
    }

    private void goToMultiImageSelector() {
        Intent intent = new Intent(context, MultiImageSelectorActivity.class);
        // 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);

        // 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);

        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);

        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                setGridView(mSelectPath.size());

            }
        }
    }


    private void setGridView(int size) {
        //1 - 3
        if (0 < size && size < 4) {
            //行
            gridView.setColumnWidth(1);
            //列
            gridView.setNumColumns(size);
        }
        //3 - 6
        if (3 < size && size < 7) {
            gridView.setColumnWidth(3);
            gridView.setNumColumns(2);
        }
        //大于6
        if (6 < size) {
            gridView.setColumnWidth(3);
            gridView.setNumColumns(3);
        }
        mImageAdapter = new GridViewBaseAdapter();
        gridView.setAdapter(mImageAdapter);

        gridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            public void onGlobalLayout() {
                final int width = gridView.getWidth();
                final int desireSize = getResources().getDimensionPixelOffset(me.nereo.multi_image_selector.R.dimen.image_size);
                final int numCount = width / desireSize;
                final int columnSpace = getResources().getDimensionPixelOffset(me.nereo.multi_image_selector.R.dimen.space_size);
                int columnWidth = (width - columnSpace * (numCount - 1)) / numCount;

                mImageAdapter.setItemSize(columnWidth);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    gridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    gridView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
    }

    private class GridViewBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mSelectPath.size();
        }

        public void setItemSize(int columnWidth) {

            if (mItemSize == columnWidth) {
                return;
            }

            mItemSize = columnWidth;

            mItemLayoutParams = new GridView.LayoutParams(mItemSize, mItemSize);

            notifyDataSetChanged();
        }


        @Override
        public String getItem(int position) {
            return mSelectPath.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(mItemLayoutParams);
            } else {
                imageView = (ImageView) convertView;
            }
            if (mItemSize > 0) {
                // 显示图片
                Picasso.with(context)
                        .load(new File(getItem(position)))
                        .placeholder(me.nereo.multi_image_selector.R.drawable.default_error)
                                //.error(R.drawable.default_error)
                        .resize(mItemSize, mItemSize)
                        .centerCrop()
                        .into(imageView);
            }
            /** Fixed View Size */
            GridView.LayoutParams lp = (GridView.LayoutParams) imageView.getLayoutParams();
            if (lp.height != mItemSize) {
                imageView.setLayoutParams(mItemLayoutParams);
            }
            return imageView;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("确认").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            this.finish();
            overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
        }
        if (item.getTitle().equals("确认")) {
            if (title.getText().toString().length() < 1) {
                Toast.makeText(context, "主题不能为空", Toast.LENGTH_LONG).show();
                return super.onMenuItemSelected(featureId, item);
            }
            dialog.show();
            postToBmob();
        }
        return super.onMenuItemSelected(featureId, item);

    }

    private void postToBmob() {
        final Post post = new Post();
        post.setTitle(title.getText().toString());
        post.setContent(content.getText().toString());
        BmobQuery<StudentUser> querry = new BmobQuery<>();
        MyPreferenceManager.init(context);
        String account = MyPreferenceManager.getString("admin_system_account", "").trim();
        String password = MyPreferenceManager.getString("admin_system_password", "").trim();
        querry.addWhereEqualTo("username", account);
        querry.addWhereEqualTo("password", password);
        querry.findObjects(getApplication(), new FindListener<StudentUser>() {
            @Override
            public void onSuccess(List<StudentUser> list) {
                post.setAuthor(list.get(0));
                BmobRemoteDateManger.getInstance(context).add(post, new SaveListener() {
                    @Override
                    public void onSuccess() {
                        Loger.V("保存post成功");
                        if (mSelectPath == null || mSelectPath.size() == 0) {
                            Toast.makeText(context, "发送帖子信息成功", Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                            finish();
                        } else {
                            Toast.makeText(context, "发送帖子信息成功,开始上传图片...", Toast.LENGTH_LONG).show();
                            //保存post成功 服务器未及时更新 等待1秒后上传
                            startPostImageToBmob(post);
                        }

                    }

                    @Override
                    public void onFailure(int i, String s) {
                        dialog.dismiss();
                        Loger.V("保存post失败" + i + " " + s);
                        Toast.makeText(context, "保存post失败" + i + " " + s, Toast.LENGTH_LONG).show();
                        finish();
                    }
                });
            }

            @Override
            public void onError(int i, String s) {
                dialog.dismiss();
                Loger.V("查询用户失败" + i + " " + s);
                Toast.makeText(context, "查询用户失败" + i + " " + s, Toast.LENGTH_LONG).show();
                finish();
            }
        });

    }

    int iTemp;

    private void startPostImageToBmob(final Post post) {
        BmobRemoteDateManger.getInstance(context).querry(post, new FindListener<Post>() {
            @Override
            public void onSuccess(List<Post> list) {
                post.setObjectId(list.get(0).getObjectId());
                List<String> realPath = new ArrayList<>();
                for (String path : mSelectPath) {
                    Bitmap bitmap = ImageUtil.getInstance(context).compressImageFromFile(path);
                    FileUtil.saveBitmap(new File(path).getName(), bitmap);
                    realPath.add(FileUtil.getSDPath() + "/OnMinDa/images/" + new File(path).getName());
                }
                final String files[] = realPath.toArray(new String[realPath.size()]);
                //批量上传文件开始
                BmobProFile.getInstance(context).uploadBatch(files, new UploadBatchListener() {

                    @Override
                    public void onSuccess(boolean isFinish, final String[] fileNames, String[] urls) {
                        if (isFinish) {
                            for (int i = 0; i < fileNames.length; i++) {
                                iTemp = i + 1;
                                PostImage_1 image = new PostImage_1();
                                image.setPost(post);
                                image.setImageUrl(urls[i]);
                                image.setImageSize(new File(files[i]).length() + "");
                                image.setImageName(fileNames[i]);
                                image.save(context, new SaveListener() {
                                    @Override
                                    public void onSuccess() {
                                        if (iTemp == fileNames.length) {
                                            dialog.dismiss();
                                            Toast.makeText(context, "上传所有文件成功", Toast.LENGTH_LONG).show();
                                            finish();
                                        }
                                    }

                                    @Override
                                    public void onFailure(int i, String s) {
                                        dialog.dismiss();
                                        Toast.makeText(context, "上传文件失败" + " " + i + " " + s, Toast.LENGTH_LONG).show();
                                        finish();
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onProgress(int curIndex, int curPercent, int total, int totalPercent) {
                        dialog.setProgress(totalPercent);
                    }

                    @Override
                    public void onError(int statuscode, String errormsg) {
                        dialog.dismiss();
                        Toast.makeText(context, "上传文件失败" + " " + statuscode + " " + errormsg, Toast.LENGTH_LONG).show();
                        finish();
                    }
                });
            }


            @Override
            public void onError(int i, String s) {
                Toast.makeText(context, "查询上传帖子失败" + i + " " + s, Toast.LENGTH_LONG).show();
            }
        });

    }

    @Override
    public void onSingleImageSelected(String path) {
        // 当选择模式设定为 单选/MODE_SINGLE, 这个方法就会接受到Fragment返回的数据
    }

    @Override
    public void onImageSelected(String path) {
        // 一个图片被选择是触发，这里可以自定义的自己的Actionbar行为
    }

    @Override
    public void onImageUnselected(String path) {
        // 一个图片被反选是触发，这里可以自定义的自己的Actionbar行为
    }

    @Override
    public void onCameraShot(File imageFile) {
        // 当设置了使用摄像头，用户拍照后会返回照片文件
    }
}
